import unittest
from datetime import datetime
import pandas as pd
import pytz
from pytz import timezone
import numpy as np


# 重建matplotlib字体缓存以确保识别系统字体
from utils.date_utils import DateTimeCombiner


def calculate_equipment_valid_days(df_equipment_entity, start_time, end_time):
    """
    计算每台设备的有效出勤天数，考虑设备创建时间
    
    Args:
        df_equipment_entity: 设备实体数据DataFrame
        start_time: 统计开始时间（datetime对象）
        end_time: 统计结束时间（datetime对象）
    
    Returns:
        DataFrame: 包含每台设备有效出勤天数的数据
    """

    # 复制设备数据
    df_valid_days = df_equipment_entity.copy()

    # 1. 向量化解析创建时间
    # 使用errors='coerce'将无法解析的日期转换为NaT (Not a Time)
    df_valid_days['创建时间'] = pd.to_datetime(df_valid_days['createDate'], errors='coerce')
    # 移除时区信息，确保与start_time和end_time的比较一致
    df_valid_days['创建时间'] = df_valid_days['创建时间'].dt.tz_localize(None)

    # 确保start_time和end_time是朴素日期时间
    start_time_naive = start_time.replace(tzinfo=None) if start_time.tzinfo else start_time
    end_time_naive = end_time.replace(tzinfo=None) if end_time.tzinfo else end_time

    # 获取日期部分用于比较（使用datetime.replace替代normalize）
    create_date_day = df_valid_days['创建时间'].dt.floor('D')  # 使用floor('D')替代normalize()
    start_date_day = datetime(start_time_naive.year, start_time_naive.month, start_time_naive.day)
    end_date_day = datetime(end_time_naive.year, end_time_naive.month, end_time_naive.day)

    # 计算总统计天数
    total_days = (end_date_day - start_date_day).days + 1

    # 2. 向量化计算有效出勤天数
    # 默认所有设备的有效天数为total_days (包括创建时间无效或早于统计开始时间的情况)
    df_valid_days['有效出勤天数'] = total_days

    # 情况1: 设备创建日期晚于统计结束日期，有效天数为0
    condition_after_end_day = create_date_day > end_date_day
    df_valid_days['有效出勤天数'] = np.where(condition_after_end_day, 0, df_valid_days['有效出勤天数'])

    # 情况2: 设备创建日期在统计周期内 (start_date_day <= create_date_day <= end_date_day)
    # 并且创建时间有效 (notna())
    condition_in_period_day = (create_date_day >= start_date_day) & \
                              (create_date_day <= end_date_day) & \
                              create_date_day.notna()

    # 计算天数差，并加1（包含结束日）
    # 使用日期部分进行计算
    days_in_period = (end_date_day - create_date_day).dt.days + 1
    df_valid_days['有效出勤天数'] = np.where(condition_in_period_day, days_in_period, df_valid_days['有效出勤天数'])

    return df_valid_days


def generate_report_tables(complete_stats,member_name):
    tables_for_report = {}
    basic_info_content = f"""
       <div class="basic-info-section">
           <h3>基础信息</h3>
           <table class="info-table">
               <tr><td>机构名称</td><td>{member_name}</td></tr>
               <tr><td>统计周期</td><td>{str(complete_stats['time_range']['start'])[:10]} 至 {str(complete_stats['time_range']['end'])[:10]}</td></tr>
               <tr><td>统计天数</td><td>{complete_stats['summary'][0]['实际统计天数']}天</td></tr>
               <tr><td>区域数量</td><td>{len(complete_stats['region_scores'])}个</td></tr>
               <tr><td>项目数量</td><td>{len(complete_stats['project_scores'])}个</td></tr>
               <tr><td>设备总数</td><td>{len(complete_stats['summary'])}台</td></tr>
           </table>
       </div>
       """

    tables_for_report['attendance_analysis'] = f"""
       <div class="attendance-section">
           <h3>☆综合评分</h3>
           <table class="data-table">
               <tr><td>综合得分</td><td class="{'highlight-good' if complete_stats['overall_score']['综合分'] > 70 else 'highlight-bad'}">{round(complete_stats['overall_score']['综合分'], 2)}</td></tr>
               <tr><td>可用性</td><td>{complete_stats['overall_score']['A_可用性']}</td></tr>
               <tr><td>出勤覆盖</td><td>{complete_stats['overall_score']['C_出勤覆盖']}</td></tr>
               <tr><td>合规达标</td><td>{complete_stats['overall_score']['P_合规达标']}</td></tr>
               <tr><td>利用强度</td><td>{complete_stats['overall_score']['U_强度利用']}</td></tr>
               <tr><td>一致性</td><td>{complete_stats['overall_score']['S_一致性']}</td></tr>
               <tr><td>可靠性</td><td>{complete_stats['overall_score']['R_可靠性']}</td></tr>
           </table>
       </div>
       """

    region_rows = ""
    list_region = complete_stats['region_scores']
    list_region.sort(key=lambda x: x['综合分'], reverse=True)
    # if len(list_region) > 1:
    for i, device in enumerate(list_region, 1):
        work_time = device.get('总工作时间', 0)


        # status_class = "highlight-good" if i <= 2 else (
        #     "highlight-warning" if i <= len(rankings['all_devices']) - 2 else "highlight-bad")

        region_rows += f"""
                <tr>
                    <td>{i}</td>
                    <td>{device.get('region_name', '未知')}</td>
                    <td>{round(device['A_可用性'], 2)}</td>
                    <td>{round(device['C_出勤覆盖'], 2)}</td>
                    <td>{round(device['P_合规达标'], 2)}</td>
                    <td>{round(device['U_强度利用'], 2)}</td>
                    <td>{round(device['S_一致性'], 2)}</td>
                    <td>{round(device['R_可靠性'], 2)}</td>
                    <td>{round(device.get('综合分', '未知'), 2)}</td>
                </tr>
                """
    tables_for_report['region_rankings'] = f"""
            <div class="device-rankings-section">
                <h3>☆区域排名 (A_可用性  C_出勤覆盖  P_合规达标  U_强度利用  S_一致性  R_可靠性)</h3>
                <table class="data-table">
                    <thead>
                        <tr><th>排名</th><th>大区</th>
                        <th>A</th>
                           <th>C</th>
                           <th>P</th>
                           <th>U</th>
                           <th>S</th>
                           <th>R</th>
                        <th>综合</th></tr>
                    </thead>
                    <tbody>
                        {region_rows}
                    </tbody>
                </table>
            </div>
            """


    list_project = complete_stats['project_scores']
    list_project.sort(key=lambda x: x['综合分'], reverse=True)
    # if len(list_region) > 1:
    project_rows = ""
    for i, device in enumerate(list_project, 1):
        work_time = device.get('总工作时间', 0)

        # status_class = "highlight-good" if i <= 2 else (
        #     "highlight-warning" if i <= len(rankings['all_devices']) - 2 else "highlight-bad")

        project_rows += f"""
                   <tr>
                       <td>{i}</td>
                       <td>{device.get('project_name', '未知')}</td>
                          <td>{round(device['A_可用性'],2)}</td>
                    <td>{round(device['C_出勤覆盖'],2)}</td>
                    <td>{round(device['P_合规达标'],2)}</td>
                   <td>{round(device['U_强度利用'],2)}</td>
                    <td>{round(device['S_一致性'],2)}</td>
                    <td>{round(device['R_可靠性'],2)}</td>
                       <td>{round(device.get('综合分', 0), 2)}</td>
                   </tr>
                   """
    tables_for_report['project_rankings'] = f"""
               <div class="device-rankings-section">
                  <h3>☆项目排名 (A_可用性  C_出勤覆盖  P_合规达标  U_强度利用  S_一致性  R_可靠性)</h3>
                   <table class="data-table">
                       <thead>
                           <tr><th></th><th>项目</th>
                           <th>A</th>
                           <th>C</th>
                           <th>P</th>
                           <th>U</th>
                           <th>S</th>
                           <th>R</th>
                           <th>综合</th>
                           </tr>
                       </thead>
                       <tbody>
                           {project_rows}
                       </tbody>
                   </table>
               </div>
               """
    list_equipment = complete_stats['monthly_scores']
    list_equipment.sort(key=lambda x: x['综合分'], reverse=True)
    # if len(list_region) > 1:
    equipment_rows = ""
    for i, device in enumerate(list_equipment, 1):
        # status_class = "highlight-good" if i <= 2 else (
        #     "highlight-warning" if i <= len(rankings['all_devices']) - 2 else "highlight-bad")

        equipment_rows += f"""
                          <tr>
                              <td>{i}</td>
                              <td>{device.get('imei')[-6:]}</td>
                              <td>{device.get('project_name', '未知')}</td>
                              <td>{device.get('type', '未知')}</td>
                                 <td>{round(device['A_可用性'],2)}</td>
                            <td>{round(device['C_出勤覆盖'],2)}</td>
                            <td>{round(device['P_合规达标'],2)}</td>
                           <td>{round(device['U_强度利用'],2)}</td>
                            <td>{round(device['S_一致性'],2)}</td>
                            <td>{round(device['R_可靠性'],2)}</td>
                              <td>{round(device.get('综合分', 0), 2)}</td>
                          </tr>
                          """
        tables_for_report['equipment_rankings'] = f"""
                      <div class="device-rankings-section">
                          <h3>☆设备排名 (A_可用性  C_出勤覆盖  P_合规达标  U_强度利用  S_一致性  R_可靠性)</h3>
                       
                          <table class="data-table">
                              <thead>
                                  <tr><th></th><th>编号后6位</th><th>项目</th><th>型号</th>
                                  <th>A</th>
                                   <th>C</th>
                                   <th>P</th>
                                   <th>U</th>
                                   <th>S</th>
                                   <th>R</th>
                                  <th>综合</th></tr>
                              </thead>
                              <tbody>
                                  {equipment_rows}
                              </tbody>
                          </table>
                      </div>
                      """
    tables_for_report['basic_info'] = basic_info_content
    list_equipment_summary = complete_stats['summary']
    list_equipment_summary.sort(key=lambda x: x['总工作时间'], reverse=True)
    # if len(list_region) > 1:
    equipment_summary_rows = ""
    for i, device in enumerate(list_equipment_summary, 1):
        # status_class = "highlight-good" if i <= 2 else (
        #     "highlight-warning" if i <= len(rankings['all_devices']) - 2 else "highlight-bad")
        avg_day = 0
        if device.get('可工作天数') > 0:
            avg_day = round(device.get('总工作时间')/device.get('可工作天数'),2)
        equipment_summary_rows += f"""
                              <tr>
                                  <td>{device.get('imei')[-6:]}</td>
                                  <td>{device.get('project_name', '未知')}</td>
                                  <td>{device.get('总工作时间', '未知')}</td>
                                  <td>{device.get('出勤天数', '未知')}</td>
                                  <td>{avg_day}</td>
                                  <td>{device.get('可工作天数', '未知')}</td>
                                  <td>{device.get('维修停机天数', '未知')}</td>
                              </tr>
                              """
        tables_for_report['equipment_summary_rankings'] = f"""
                          <div class="device-rankings-section">
                              <h3>☆设备使用明细 </h3>
                              <table class="data-table">
                                  <thead>
                                      <tr><th>编号后6位</th><th>项目名称</th><th>总工作时间</th><th>出勤天数</th><th>日均时长</th><th>可用天数</th><th>维修停机天数</th></tr>
                                  </thead>
                                  <tbody>
                                      {equipment_summary_rows}
                                  </tbody>
                              </table>
                          </div>
                          """
    return tables_for_report


def render_final_report(report_tables, ai_content, member_name, start_time, end_time):
    """
    渲染最终报告HTML

    Args:
        report_tables: HTML表格
        ai_content: AI生成的分析内容
        member_name: 机构名称
        start_time: 开始时间
        end_time: 结束时间

    Returns:
        str: 最终的HTML报告
    """
    # 解析AI内容为段落（增强版）
    ai_sections = {}
    current_section = None
    current_content = []

    print(f"🔍 开始解析AI内容，总长度: {len(ai_content)} 字符")

    lines = ai_content.split('\n')
    for i, line in enumerate(lines):
        line = line.strip()

        # 检测多种标题格式
        is_title = False
        title_text = None

        # 格式1：**标题**
        if line.startswith('**') and line.endswith('**') and len(line) > 4:
            is_title = True
            title_text = line.strip('*').strip()
        # 格式2：第一部分 - 标题
        elif line.startswith('第') and ('部分' in line or '部分 -' in line):
            is_title = True
            title_text = line
        # 格式3：## 标题
        elif line.startswith('##') and len(line) > 3:
            is_title = True
            title_text = line.strip('#').strip()
        # 格式4：单独的标题行（如果前后都是空行）
        elif (line and not line.startswith('**') and
              ('总结' in line or '发现' in line or '问题' in line or '亮点' in line or '建议' in line or '重点' in line) and
              len(line) < 50):
            # 检查是否像标题（短，包含关键词）
            if i > 0 and i < len(lines) - 1:
                prev_line = lines[i - 1].strip()
                next_line = lines[i + 1].strip()
                if not prev_line and next_line:  # 前面是空行，后面有内容
                    is_title = True
                    title_text = line

        if is_title:
            # 保存前一节内容
            if current_section and current_content:
                content_text = '<br><br>'.join(current_content)
                ai_sections[current_section] = content_text
                print(f"✅ 保存章节: {current_section} ({len(content_text)} 字符)")

            # 开始新节
            current_section = title_text
            current_content = []
            print(f"🆕 开始新章节: {current_section}")
        elif line and current_section:
            current_content.append(line)
        elif line and not current_section:
            # 如果还没有章节标题，但有内容，创建一个默认章节
            if not current_section:
                current_section = "主要分析内容"
                current_content = []
                print(f"🆕 创建默认章节: {current_section}")
            current_content.append(line)

    # 保存最后一节
    if current_section and current_content:
        content_text = '<br><br>'.join(current_content)
        ai_sections[current_section] = content_text
        print(f"✅ 保存最后章节: {current_section} ({len(content_text)} 字符)")

    # 如果完全没有解析出内容，创建一个兜底章节
    if not ai_sections and ai_content.strip():
        ai_sections["智能分析"] = ai_content.replace('\n', '<br>')
        print(f"🛡️ 创建兜底章节，原始内容长度: {len(ai_content)}")

    print(f"📊 AI内容解析完成，共{len(ai_sections)}个章节: {list(ai_sections.keys())}")

    # 构建最终HTML
    html_content = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>{member_name} 设备工作分析报告</title>
        <style>
            body {{
                font-family: "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif;
                line-height: 1.6;
                margin: 40px;
                color: #333;
                background-color: #fff;
            }}
            .report-header {{
                text-align: center;
                margin-bottom: 40px;
                border-bottom: 2px solid #1f4e79;
                padding-bottom: 20px;
            }}
            .report-title {{
                font-size: 28px;
                color: #1f4e79;
                font-weight: bold;
                margin-bottom: 10px;
            }}
            .report-subtitle {{
                font-size: 18px;
                color: #666;
                margin-bottom: 20px;
            }}
            .data-table {{
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 25px;
                font-size: 14px;
            }}
            .data-table th, .data-table td {{
                border: 1px solid #ddd;
                padding: 5px;
                font-size: 10px;
                text-align: center;
            }}
            .data-table th {{
                background-color: #1f4e79;
                color: white;
                font-weight: bold;
            }}
            .data-table tr:nth-child(even) {{
                background-color: #f9f9f9;
            }}
            .highlight-good {{
                color: #28a745;
                font-weight: bold;
            }}
            .highlight-bad {{
                color: #dc3545;
                font-weight: bold;
            }}
            .section {{
                margin: 30px 0;
                padding: 20px;
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                background-color: #fafafa;
            }}
            .section h3 {{
                color: #1f4e79;
                margin-top: 0;
                margin-bottom: 14px;
                font-size: 14px;
            }}
            .section h4 {{
                color: #1f4e79;
                margin-bottom: 12px;
                border-bottom: 1px solid #e0e0e0;
                padding-bottom: 8px;
            }}
            .ai-analysis {{
                background-color: #f8f9fa;
                padding: 25px;
                border-left: 4px solid #1f4e79;
                margin: 30px 0;
            }}
            .ai-analysis h4 {{
                color: #1f4e79;
                margin-bottom: 15px;
            }}
            .ai-content {{
                text-align: justify;
                line-height: 1.8;
                margin-bottom: 20px;
            }}
            .info-table {{
                width: 100%;
                border-collapse: collapse;
            }}
            .info-table td {{
                border: 1px solid #ddd;
                padding: 8px;
                text-align: left;
            }}
            .info-table td:first-child {{
                background-color: #f0f0f0;
                font-weight: bold;
                width: 30%;
            }}
        </style>
    </head>
    <body>
        <div class="report-header">
            <div class="report-title">{member_name} 清洁设备工作分析报告</div>
            <div class="report-subtitle">{DateTimeCombiner.parse_iso_to_date(start_time).strftime('%Y年%m月%d日')} 至 {DateTimeCombiner.parse_iso_to_date(end_time).strftime('%Y年%m月%d日')}</div>
        </div>

        <div class="section">
            {report_tables.get('basic_info', '')}
        </div>
        <div class="section">
            {report_tables.get('attendance_analysis', '')}
        </div>
        <div class="section">
            {report_tables.get('region_rankings', '')}
        </div> 
        <div class="section">
            {report_tables.get('project_rankings', '')}
        </div> 
        <div class="section">
            {report_tables.get('equipment_rankings', '')}
        </div> 
        <div class="section">
            {report_tables.get('equipment_summary_rankings', '')}
        </div>
        <div class="ai-analysis">
            <h3>🤖 专业分析</h3>
            {''.join([f'<div class="ai-content"><h4>{title}</h4><div>{content}</div></div>' for title, content in ai_sections.items()])}
        </div>
       
    </body>
    </html>
    """

    return html_content

# < div
#
#
# class ="section" >
#
#
# {report_tables.get('attendance_analysis', '')}
# < / div >
#
# < div
#
#
# class ="section" >
#
#
# {report_tables.get('region_breakdown', '')}
# < / div >
#
# < div
#
#
# class ="section" >
#
#
# {report_tables.get('top_devices', '')}
# < / div >
#
# < div
#
#
# class ="section" >
#
#
# {report_tables.get('bottom_devices', '')}
# < / div >
#
# < div
#
#
# class ="section" >
#
#
# {report_tables.get('anomaly_detection', '')}
# < / div >
#
# < div
#
#
# class ="section" >
#
#
# {report_tables.get('efficiency_distribution', '')}
# < / div >
#
# < div
#
#
# class ="section" >
#
#
# {report_tables.get('summary_stats', '')}
# < / div >